from infra.handler import BaseHandler
from .comment_db import create_comment
from .comment_db import get_comments
from .comment_db import delete_comment
from domain.message.message_db import insert_message
from domain.activity.activity_db import get_activity_info
import json

class CommentHandler(BaseHandler):
    async def get(self):
        """获取评论列表"""
        try:
            user_id, _ = self.get_current_user()
            if not user_id:
                self.write(json.dumps({"code": 404, "msg": "User not found"}))
                return
            # 获取查询参数                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    
            activity_id = self.get_argument('activity_id', default=None)
            page = int(self.get_argument('page', default='1'))
            page_size = int(self.get_argument('page_size', default='10'))
            # 验证必需参数
            if not activity_id:
                return self.error('缺少活动ID')
            
            # TODO: 从数据库获取评论列表
            comments = await get_comments(activity_id, page, page_size)
            # 构建返回数据
            response_data = {
                'comments': comments,
                'total': len(comments)
            }
            self.write(json.dumps({
                "code": 200,
                "msg": "success",
                "data": response_data
            }))
        except Exception as e:
            self.write(json.dumps({
                "code": 404,
                "msg": str(e)
            }))
    async def post(self):
        """创建评论"""
        try:
            user_id, _ = self.get_current_user()
            if not user_id:
                self.write(json.dumps({"code": 404, "msg": "User not found"}))
                return
            # 获取请求数据
            data = json.loads(self.request.body)
            # 验证必需字段
            if not data.get('content') and not data.get('image'):
                return self.error('评论内容和图片至少需要一个')

            if not data.get('activity_id'):
                return self.error('缺少活动ID')
            
            # 获取活动信息
            success, activity_info = await get_activity_info(data['activity_id'], user_id)
            if not success:
                self.write(json.dumps({"code": 404, "msg": "活动不存在"}))
                return
            # 构建评论数据
            comment_data = {
                'user_id': user_id,
                'activity_id': data['activity_id'],
                'content': data.get('content', ''),
                'parent_id': data.get('parent_id', 0),
                'image': data.get('image', '')
            }
            # print(comment_data)
            ret, comment = await create_comment(comment_data)
            if not ret:
                self.write(json.dumps({
                    "code": 404,
                    "msg": comment
                }))
                return
            # 如果是回复其他评论，给被回复的用户发送通知
            if comment_data.get('parent_id', 0) > 0:
                await insert_message(
                    type="interaction",
                    title="新的评论回复",
                    content=f"有用户回复了你的评论：{comment_data.get('content', '[图片评论]')}",
                    receiver_id=comment['parent_user_id'],  # 被回复的用户ID
                    sender_id=user_id,
                    activity_id=comment_data['activity_id'],
                    comment_id=comment['id']
                )
            # 如果评论者不是活动创建者，给活动创建者发送通知
            if user_id != activity_info['created_user_id']:
                await insert_message(
                    type="interaction",
                    title="新的活动评论",
                    content=f"有用户评论了你的活动：{comment_data.get('content', '[图片评论]')}",
                    receiver_id=activity_info['created_user_id'],
                    sender_id=user_id,
                    activity_id=data['activity_id'],
                    comment_id=comment['id']
                )
            self.write(json.dumps({
                "code": 200,
                "msg": comment
            }))
        except json.JSONDecodeError:
            self.write(json.dumps({
                "code": 404,
                "msg": "Invalid JSON format"
            }))
        except Exception as e:
            self.write(json.dumps({
                "code": 404,
                "msg": str(e)
            }))
    async def delete(self):
        """删除评论"""
        try:
            # 获取当前用户ID和评论ID
            user_id, _ = self.get_current_user()
            if not user_id:
                self.write(json.dumps({"code": 404, "msg": "User not found"}))
                return
            data = json.loads(self.request.body)
            comment_id = data.get('comment_id')  # 从请求体中获取comment_id
            if not comment_id:
                self.write(json.dumps({"code": 404, "msg": "缺少评论ID"}))
                return
                
            # 删除评论
            success, message = await delete_comment(comment_id, user_id)
            
            if success:
                self.write(json.dumps({
                    "code": 200,
                    "msg": "删除成功",
                    "data": None
                }))
            else:
                self.write(json.dumps({
                    "code": 404,
                    "msg": message
                }))
                
        except Exception as e:
            self.write(json.dumps({
                "code": 404,
                "msg": str(e)
            }))
